package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.PathMatcherUtil;
import com.zzyl.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class WebInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenProperties jwtTokenProperties;
    final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        1.获取请求头
        String jwt = request.getHeader("Authorization");
        if(StrUtil.isBlank(jwt)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

//        2.解析jwt,拿出用户ID
        Claims claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), jwt);
        Long userId = Long.valueOf(claims.get("id").toString());
        if(ObjectUtil.isEmpty(userId)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }


//        3.拿到用户可访问的资源路径
        String jsonPaths = stringRedisTemplate.opsForValue().get("user:resource:path:" + userId);
        if(StrUtil.isEmpty(jsonPaths)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

//        4.拿到比较的鉴权使用的数据 (用户可访问的路径集合、用户发送请求方法名和地址）
        List<String> paths = JSON.parseArray(jsonPaths, String.class);
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String path = method + requestURI;

//        5. 验证当前请求的url是否在可访问的路径中
        boolean match = PathMatcherUtil.match(paths, path);
        if(!match) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

//        6.记录userId到ThreadLocal中，方便后续使用
        ThreadLocalUtil.set(userId);



        return true; // 放行
    }
}
